package com.team.activity.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.team.activity.domain.BizActivity;
import com.team.activity.domain.BizActivityLog;
import com.team.activity.domain.BizActivityPushLog;
import com.team.activity.domain.dto.BizActivityDto;
import com.team.activity.exception.CustomException;
import com.team.activity.mapper.BizActivityLogMapper;
import com.team.activity.mapper.BizActivityMapper;
import com.team.activity.mapper.BizActivityPushLogMapper;
import com.team.activity.mapper.BizUserFollowMerchantMapper;
import com.team.activity.service.BizActivityService;
import com.team.activity.service.WebSocketService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class BizActivityServiceImpl implements BizActivityService {

    @Autowired
    private BizActivityMapper activityMapper;
    @Autowired
    private BizActivityLogMapper activityLogMapper;
    @Autowired
    private BizUserFollowMerchantMapper followMerchantMapper;
    @Autowired
    private WebSocketService webSocketService;
    @Autowired
    private BizActivityPushLogMapper activityPushLogMapper;

    @Transactional( rollbackFor = Exception.class)
    @Override
    public String publishActivity(BizActivityDto activity, boolean isPlatform) {
        try{
            // 检查活动是否合法
            checkActivity(activity , isPlatform);
            // 合法，发布活动
            BizActivity bean = BeanUtil.toBean(activity, BizActivity.class);
            bean.setStatus("1");
            activityMapper.insert(bean);
            // 商铺活动，通知所有关注的用户
            if (!isPlatform) {
                // 商家活动，通知关注该商户的用户
                // 查找关注该商户的用户ID
                List<Long> userIds = followMerchantMapper.selectUserIdsByMerchantId(activity.getMerchantId());
                // 发送通知给每个用户
                for (Long userId : userIds) {
                    BizActivityPushLog bizActivityPushLog = new BizActivityPushLog();
                    bizActivityPushLog.setActivityId(bean.getId());
                    bizActivityPushLog.setUserId(userId);
                    bizActivityPushLog.setStatus(0);
                    // 记录到消息推送表中
                    activityPushLogMapper.insert(bizActivityPushLog);
                    // 推送最新未读数
                    webSocketService.sendActivityNotification(userId, bean.getId());
                }
            }
            return "活动发布成功";
        }catch (CustomException e){
            return e.getMsg();
        }
    }

    @Transactional( rollbackFor = Exception.class)
    @Override
    public String readActivity(Long activityId, Long userId) {
        try{
            // 1. 检查活动是否存在，并获取活动所属商户ID（核心：通过活动找商户）
            BizActivity activity = checkActivityExists(activityId); // 改造check方法，返回活动对象
            Long merchantId = activity.getMerchantId(); // 活动所属商户ID


            // 2. 核心状态判断
            // 2.1 用户当前是否关注该商户（无论何时关注）
            boolean currentFollow = followMerchantMapper.checkUserFollowMerchant(userId, merchantId) == 1;
            // 2.2 用户是否有该活动的推送记录（仅活动发布时关注的用户会有推送记录）
            BizActivityPushLog pushLog = activityPushLogMapper.selectByActivityIdAndUserId(activityId, userId);
            boolean hasPushRecord = (pushLog != null);


            // 3. 处理阅读记录和未读状态
            // 3.1 检查用户是否已存在阅读记录
            BizActivityLog existLog = activityLogMapper.selectByActivityIdAndUserId(activityId, userId);

            if (hasPushRecord) {
                // 场景1：用户在活动发布时关注商户（有推送记录）
                // 无论现在是否取消关注，阅读时都需将未读状态改为已读
                if (pushLog.getStatus() == 0) { // 未读状态
                    activityPushLogMapper.updateByActivityAndUserId(activityId, userId); // 更新推送记录为已读
                }
                // 更新阅读记录（已有则次数+1，无则新增）
                if (existLog != null) {
                    activityLogMapper.update(activityId , userId); // 次数+1
                } else {
                    BizActivityLog newLog = new BizActivityLog();
                    newLog.setActicityId(activityId); // 修正拼写错误
                    newLog.setUserId(userId);
                    newLog.setCount(1L);
                    activityLogMapper.insert(newLog);
                }

            } else {
                // 场景2：用户在活动发布时未关注商户（无推送记录）
                // 可能是后来关注的，或从未关注，阅读时无需处理未读状态（因为没推送过）
                if (existLog != null) {
                    activityLogMapper.update(activityId , userId); // 次数+1
                } else {
                    BizActivityLog newLog = new BizActivityLog();
                    newLog.setActicityId(activityId); // 修正拼写错误
                    newLog.setUserId(userId);
                    newLog.setCount(1L);
                    activityLogMapper.insert(newLog);
                }
            }
            // 4. 推送最新未读消息数（仅统计有推送记录且未读的数量）
            webSocketService.sendActivityNotification(userId, activityId);

            return "活动阅读成功";
        }catch (CustomException e){
            return e.getMsg();
        }
    }

    // 改造检查活动存在的方法，返回活动对象（方便获取商户ID）
    private BizActivity checkActivityExists(Long activityId) {
        BizActivity activity = activityMapper.selectByPrimaryKey(activityId);
        if (activity == null) {
            throw new CustomException("活动不存在");
        }
        return activity;
    }

    //检查活动是否合法
    public boolean checkActivity(BizActivityDto activity , boolean isPlatform) {
        // 检查活动标题是否为空
        if (activity.getTitle() == null || activity.getTitle().isEmpty()) {
            throw new CustomException("活动标题不能为空");
        }
        // 检查商户ID是否为空
        if (activity.getMerchantId() == null) {
            throw new CustomException("商户ID不能为空");
        }
        if (activity.getMerchantId() == 0 && !isPlatform) {
            // 再次确认是否为平台活动
            throw new CustomException("活动类型不匹配");
        }
        //检查活动描述是否为空
        if (activity.getDescription() == null || activity.getDescription().isEmpty()) {
            throw new CustomException("活动描述不能为空");
        }
        // 检查活动开始时间是否为空
        if (activity.getStartTime() == null) {
            throw new CustomException("活动开始时间不能为空");
        }
        // 检查活动结束时间是否为空
        if (activity.getEndTime() == null) {
            throw new CustomException("活动结束时间不能为空");
        }
        // 检查活动结束时间是否早于活动开始时间
        if (activity.getEndTime().before(activity.getStartTime())) {
            throw new CustomException("活动结束时间不能早于活动开始时间");
        }
        return true;
    }


} 